package com.ghck.server.controller;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.DictDiseaseKey;
import com.ghck.server.model.Disease;
import com.ghck.server.model.DiseaseCategoryDict;
import com.ghck.server.model.DiseaseKeyword;
import com.ghck.server.model.DiseaseReq;
import com.ghck.server.model.query.DiseaseKeywordQuery;
import com.ghck.server.model.query.DiseaseQuery;
import com.ghck.server.model.response.BodypartDictRes;
import com.ghck.server.model.response.DiseaseRes;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.service.BodypartDictService;
import com.ghck.server.service.DictDiseaseKeyService;
import com.ghck.server.service.DiseaseCategoryDictService;
import com.ghck.server.service.DiseaseKeywordService;
import com.ghck.server.service.DiseaseService;
import com.ghck.server.utils.IntegerUtil;

/**
 * 疾病相关接口
 * @author chenxuan
 * 
 * t_disease
 * dict_bodypart
 * r_disease_bodypart
 */
@Controller
@RequestMapping(value="/disease")
public class DiseaseController {
	
	Logger logger = LoggerFactory.getLogger(DiseaseController.class);

	@Autowired
	private DiseaseService diseaseService;
	
	@Autowired
	DiseaseCategoryDictService diseaseCategoryDictService;
	
	@Autowired
	private DictDiseaseKeyService dictDiseaseKeyService;
	
	@Autowired
	private DiseaseKeywordService diseaseKeywordService;
	
	@Autowired
	private BodypartDictService bodypartDictService;
	
	/**
	 * 疾病分类列表
	 * @return
	 */
	@RequestMapping(value="/category/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseCategoryDict> getDiseaseCategoryDictList(){
		ResultList<DiseaseCategoryDict> list = new ResultList<DiseaseCategoryDict>();
		list.setItemList(diseaseCategoryDictService.findAll());
		return list;
	}
	
	/**
	 * 身体部位列表
	 * @return
	 */
	@RequestMapping(value="/bodypart/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<BodypartDictRes> getBodypartDictList(){
		long start = System.currentTimeMillis();
		ResultList<BodypartDictRes> list = new ResultList<BodypartDictRes>();
		List<BodypartDictRes> result = bodypartDictService.findAll();
		//List<BodypartDictRes> result = bodypartDictService.findAllWithCache();
		list.setItemList(result);
		System.err.println("=============Cost:"+(System.currentTimeMillis()-start));
		return list;
	}
	
	@RequestMapping(value="/symptom/disease/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseRes> getDiseaseListForSymptomId(DiseaseQuery query){
		ResultList<DiseaseRes> resultList = new ResultList<DiseaseRes>();
		List<DiseaseRes> diseaseRes = diseaseService.findDiseaseListForSymptomId(query);
		resultList.setItemList(diseaseRes);
		return resultList;
	}
	
	@RequestMapping(value="/detail/{diseaseId}",method=RequestMethod.GET)
	@ResponseBody
	public ResultObject<Disease> getDiseaseById(@PathVariable("diseaseId") Integer diseaseId){
		Disease disease = diseaseService.findDiseaseByIdWithCache(diseaseId);
		
		return new ResultObject<>(disease);
	}
	
	
	/**
	 * 疾病详情
	 * @return
	 */
	@RequestMapping(value="/detail",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DictDiseaseKey> getDiseaseCategoryDictList(DiseaseQuery query){
		if(query.getId()== null || query.getId() == 0){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"疾病ID不能为空");
		}
		return new ResultList<DictDiseaseKey>(dictDiseaseKeyService.queryDictDiseaseKey(query.getId()));
	}
	
	/**
	 * 疾病热词列表
	 * @return
	 */
	@RequestMapping(value="/hotword/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseKeyword> getDiseaseHotwordList(DiseaseKeywordQuery query){
		ResultList<DiseaseKeyword> resultList =  new ResultList<DiseaseKeyword>();
		List<DiseaseKeyword> result = null;
		List<DiseaseKeyword> all = diseaseKeywordService.findDiseaseKeywordByQueryWithCache();
		if (CollectionUtils.isNotEmpty(all)) {
			Integer total = all.size();
			query.setCount(total);
			Integer start = query.getStart();
			Integer limit = query.getLimit();
			if(start!=null && IntegerUtil.isPositiveInteger(limit)){
				if(start>=0 && start<total){
					int fromIndex = start;
					int toIndex = start+limit;
					if((start+limit)>total){
						toIndex = total;
					}
					result = all.subList(fromIndex, toIndex);
				}
			}else{
				result = all;
			}
		}else{
			query.setCount(0);
		}
		resultList.setExt(query);
		resultList.setItemList(result);
		return resultList;
	}
	/**
	 * 疾病详情
	 * @return
	 */
	@RequestMapping(value="/search",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseRes> diseaseSearch(DiseaseQuery query){
//		if(null == keyword){
//			if(query.getKeyword() == null || query.getKeyword().trim().isEmpty()){
//				throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"搜索关键字不能为空");
//			}
//			
//		}else{
//			query.setKeyword(keyword);
//		}
		if(StringUtils.isEmpty(query.getKeyword())){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"搜索关键字不能为空");
		}
		List<DiseaseRes> list = diseaseService.findDiseaseByQuery(query);
		return new ResultList<DiseaseRes>(list);
	}
	
	/**
	 * 疾病详情
	 * @return
	 */
	@RequestMapping(value="/manager/list",method=RequestMethod.GET)
	@ResponseBody
	public ResultList<DiseaseRes> diseaseManagerList(DiseaseQuery query){
//		if(null == keyword){
//			if(query.getKeyword() == null || query.getKeyword().trim().isEmpty()){
//				throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"搜索关键字不能为空");
//			}
//			
//		}else{
//			query.setKeyword(keyword);
//		}
		ResultList<DiseaseRes> resultList  = new ResultList<DiseaseRes>();
		List<DiseaseRes> itemList = diseaseService.managerList(query);
		resultList.setItemList(itemList);
		Integer rowCount = diseaseService.countDiseaseByQuery(query);
		resultList.setExt(rowCount);	
		return resultList;
	}
	
	
	//==============================管理平台========================================
	
	/**
	 *  新增疾病 
	 *  每次讲全量 bodypartIds传上来
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> addDisease(@RequestBody DiseaseReq req){
		List<Integer> bodypartIds = req.getBodypartIds();
		if (CollectionUtils.isEmpty(bodypartIds)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"所属身体ID列表不能为空");
			logger.info("添加疾病失败",exception);
			throw exception;
		}
		Integer id = diseaseService.insertDisease(req);
		return new ResultObject<>(id);
	}
	
	
	/**
	 * 修改疾病
	 */
	@RequestMapping(value="/modify/{diseaseId}",method=RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> modifyDisease(@PathVariable("diseaseId") Integer diseaseId, @RequestBody DiseaseReq req){
		List<Integer> bodypartIds = req.getBodypartIds();
		if(!IntegerUtil.isPositiveInteger(diseaseId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"指定diseaseId为空");
			logger.info("修改疾病失败",exception);
			throw exception;
		}
		if (CollectionUtils.isEmpty(bodypartIds)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"所属身体ID列表不能为空");
			logger.info("修改疾病失败",exception);
			throw exception;
		}
		req.setId(diseaseId);
		Integer id = diseaseService.updateDisease(req);
		return new ResultObject<>(id);
	}
	
	
	/**
	 * 启用疾病
	 */
	@RequestMapping(value="/enable/{diseaseId}",method=RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> enableDisease(@PathVariable("diseaseId") Integer diseaseId){
		if(!IntegerUtil.isPositiveInteger(diseaseId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"指定diseaseId为空");
			logger.info("修改疾病失败",exception);
			throw exception;
		}
		diseaseService.enableDisease(diseaseId);
		return new ResultObject<>(diseaseId);
	}
	
	
	
	/**
	 * 禁用疾病
	 */
	@RequestMapping(value="/disable/{diseaseId}",method=RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> disableDisease(@PathVariable("diseaseId") Integer diseaseId){
		if(!IntegerUtil.isPositiveInteger(diseaseId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"指定diseaseId为空");
			logger.info("修改疾病失败",exception);
			throw exception;
		}
		diseaseService.disableDisease(diseaseId);
		return new ResultObject<>(diseaseId);
	}
	
	/**
	 * 添加热词
	 */
	@RequestMapping(value="/hotword/add",method=RequestMethod.POST)
	@ResponseBody
	public ResultObject<Integer> addDiseaseHotword(@RequestBody DiseaseKeyword keyword){
		if(StringUtils.isEmpty(keyword.getName())){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"热词名称不能为空");
			logger.info("添加热词失败",exception);
			throw exception;
		}
		Integer id = diseaseKeywordService.insertDiseaseKeyword(keyword);
		
		return new ResultObject<Integer>(id);
	}
	
	
   /**
    * 修改热词
    */
	@RequestMapping(value="/hotword/modify/{keywordId}",method=RequestMethod.PUT)
	@ResponseBody
	public ResultObject<Integer> modifyDiseaseHotword(@RequestBody DiseaseKeyword keyword,@PathVariable("keywordId") Integer keywordId){
		if(IntegerUtil.isNotPositiveInteger(keywordId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"keywordId不能为空");
			logger.info("修改热词失败",exception);
			throw exception;
		}
		keyword.setId(keywordId);
		
		diseaseKeywordService.updateDiseaseKeyword(keyword);
		
		return new ResultObject<Integer>(keywordId);
	}
}